﻿using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Resources;
using System.Collections.Generic;

using SqlServer = DataCoreTechnologies.SqlServer;

namespace DataCoreTechnologies.Scribe
{
    public partial class OutputForm : Form
    {
        #region Public
        public OutputForm()
        {
            InitializeComponent();
        }
        #endregion
        #region Internal
        //Properties
        //internal UI.TreeNodeDocument ServerNode { set; private get; }
        internal List<Business.Page> Pages { set; private get; }
        //Methods
        internal void CreateDocumentation()
        {
            if (IsFolderLocationValid(txtFolderPath.Text))
            {
                _outputFolder = txtFolderPath.Text;

					 if (Pages == null || _outputFolder == "")
					     throw new InvalidOperationException("ServerNode and OutputFolder need to be set before calling this method");
					 else
					 {
					     try
					     {
					         this.Cursor = Cursors.WaitCursor;

					         if (_outputFolder.EndsWith(@"\") == false) _outputFolder += @"\";
                        
					         //Create the output folder and write any necessary images into it
					         Directory.CreateDirectory(_outputFolder + @"images");
					         string folder = _outputFolder + @"images\";
					         ResourceManager rm = Scribe.Properties.Resources.ResourceManager;

					         Image i = (Image)rm.GetObject("plus");
					         i.Save(folder + @"plus.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

					         i = (Image)rm.GetObject("minus");
					         i.Save(folder + @"minus.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

					         //Create all of the necessary html pages.
					         foreach (Business.Page page in Pages)
					         {
                           WriteToFile(page.htmlDocument.GetHtml(), page.htmlDocument.URL);
					         }

					         MessageBox.Show("Finished");

					         if (chkDisplayHtml.Checked)
					         {
					             string url = _outputFolder + @"index.html";
					             ProcessStartInfo sInfo = new ProcessStartInfo(url);
					             Process.Start(sInfo);
					         }

                        this.Close();
                    }
                    catch (Exception ex)
                    {
                        SqlServer.Diagnostic.WriteLine("Error:" + ex.Message);
                        SqlServer.Diagnostic.WriteLine("Error:" + ex.StackTrace);
                        MessageBox.Show("Error: Unable to create documentation", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                       this.Cursor = Cursors.Default;
                    }
                }
            }
        }
        #endregion
        #region Private
        //Methods
        /// <summary>
        /// Opens a file, writes the contents of the html string, and closes it
        /// </summary>
        /// <param name="html">A string containing the Html to be output</param>
        /// <param name="fileName">The full pathname of the resulting file.</param>
        private void WriteToFile(string html, string fileName)
        {
            //Changes the hard coded a href links to local ones based on the current file location
            html = html.Replace(@"http://", "");
            html = html.Replace(@"www.datacoretechnologies.com", @"http://www.datacoretechnologies.com");
            html = html.Replace(Business.Html.ServerDocument.RootFolderPath, @"images/");
            StreamWriter file = new StreamWriter(_outputFolder + fileName);
            file.Write(html);
            file.Close();
        }
        private Boolean IsFolderLocationValid(string folderLocation)
        {
            try
            {
                if (Directory.GetFiles(folderLocation).Count() != 0
                    | Directory.GetDirectories(folderLocation).Count() != 0)
                {
                    MessageBox.Show("Error: Target folder is not empty", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (DirectoryNotFoundException)
            {
                MessageBox.Show("Error: Specified directory doesn't exist", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (PathTooLongException)
            {
                MessageBox.Show("Error: Directory path is too long", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (ArgumentNullException)
            {
                MessageBox.Show("Error: You didn't specify a directory path", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (IOException)
            {
                MessageBox.Show("Error: Unable to read from file system", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Error: Invalid directory path", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("Error: You don't have write access to this folder", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            return true;
        }

        //Form events
        private void btnOK_Click(object sender, EventArgs e)
        {
            CreateDocumentation();
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fb = new FolderBrowserDialog();
            fb.ShowNewFolderButton = true;
            fb.Description = "Select Folder:";
            if (fb.ShowDialog() == DialogResult.OK)
            {
                txtFolderPath.Text = fb.SelectedPath;
                IsFolderLocationValid(txtFolderPath.Text);
            }
            fb.Dispose();
        }
        private void txtFolderPath_Leave(object sender, EventArgs e)
        {
            if (txtFolderPath.Text != "")
                IsFolderLocationValid(txtFolderPath.Text);
        }
        private void frmOutput_Load(object sender, EventArgs e)
        {

        }

        //Properties
        private string _outputFolder;
        #endregion
    }
}
